# -*- coding: utf-8 -*-
# 封装 访问 streamsets的接口
from orchid import Orchid
import time
from tools import getLogger
g_logger = getLogger("streamsetsrest")
orchid = Orchid(protocol="http", port=18630, prefix="/rest/v1", logger=g_logger)
i_headers = {
        "User-Agent": "Nsfocus/1.0",
        "Accept": "application/json",
        "Content-Type": "application/json;charset=UTF-8",
        "X-Requested-By": "Data Collector"
    }
orchid.setHeader(i_headers)
orchid.setAuthType('basic')
orchid.setBasicInfo({"pwd": "admin", "user": "admin"})


# 获取所有的pipeline QueryParam  /pipelines  GET
def getPipelines(label, includeStatus, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipelines", {"label": label, "includeStatus": includeStatus}):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip [%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipelines", "label=" + label + "&" + "includeStatus=" + includeStatus), orchid.getError())


# 启动所有的pipeline  /pipelines/start POST
def startPipelines(pipelineList, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipelines/start", pipelineList):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipelines/start", orchid.getError()))


# 新建pipeline PathParam  /pipeline/{pipelineName} PUT
def putPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipeline/" + pipelineName, None):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [PUT], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName, orchid.getError()))


# 获取pipeline配置 PathParam  /pipeline/{pipelineName} GET
def getPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipeline/" + pipelineName):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName, orchid.getError()))


# 更新pipeline配置 PathParam  /pipeline/{pipelineName} POST
def postPipeline(pipelineName, pipelineObject, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipeline/" + pipelineName, pipelineObject):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName, orchid.getError()))


# 删除pipeline配置 PathParam /pipeline/{pipelineName} DELETE
def deletePipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.delete("/pipeline/" + pipelineName):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [DELETE], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName, orchid.getError()))


# pipeline导入 PathParam  QueryParam  /pipeline/{pipelineName}/import POST
def importPipeline(pipelineName, overwrite, pipelineObject, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipeline/" + pipelineName + "/import", pipelineObject, {"overwrite": overwrite}):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/import", orchid.getError()))


# pipeline导出 PathParam /pipeline/{pipelineName}/export  GET
def exportPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipeline/" + pipelineName + "/export"):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/export", orchid.getError()))


# 停止指定pipeline PathParam /pipeline/{pipelineName}/stop POST
def stopPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipeline/" + pipelineName + "/stop", None):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/stop", orchid.getError()))


# 强行停止指定pipeline PathParam /pipeline/{pipelineName}/forceStop POST
def forceStopPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipeline/" + pipelineName + "/forceStop", None):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/forceStop", orchid.getError()))


# 启动指定pipeline PathParam /pipeline/{pipelineName}/start POST
def startPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipeline/" + pipelineName + "/start", None):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/start", orchid.getError()))


# 启动参数中所有的 pipelineName        /pipelines/start  POST
def startPipelines(pipelineNames, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipelines/start", pipelineNames):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipelines/start", orchid.getError()))


# 监测pipeline状态 PathParam  /pipeline/{pipelineName}/status GET
def checkPipeline(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipeline/" + pipelineName + "/status"):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/status", orchid.getError()))


# 删除pipeline 通过标签 QueryParam /pipelines/deleteByFiltering POST
def deleteByFiltering(label, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipelines/deleteByFiltering", None, {"label": label}):
        return orchid.getResult()
    else:
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipelines/deleteByFiltering", orchid.getError()))


# 获取指定pipeline的metrics  PathParam  /pipeline/{pipelineName}/metrics GET
def getPipelineMetrics(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipeline/" + pipelineName + "/metrics"):
        return orchid.getResult()
    else:
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/" + pipelineName + "/metrics", orchid.getError()))


# 重启streamsets /system/restart  POST
def restart(ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/system/restart", None):
        return orchid.getResult()
    else:
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/system/restart", orchid.getError()))


# -------------------------以下是主节点上（特殊）的streamsetsrest接口--------------


# 获取所有的pipeline QueryParam  /pipelines  GET
def pipelines(label, filterText, status, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipelines", {"label": label, "filterText": filterText, "includeStatus": status}):
        return orchid.getResult()
    else:
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipelines" + "?label=" + label + "&" + "filterText=" + filterText, orchid.getError()))


# 加标签 /pipelines/addLabels  object POST
def addLabels(body, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.post("/pipelines/addLabels", body):
        return orchid.getResult()
    else:
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [POST], response Error [%s]" % (
            ip, "/pipelines/addLabels", orchid.getError()))


# ---------------------------------增加pipeline额外的一些操作方法--------------------------------------------

# 导入 pipeline
def postPipeline_not_rest(ip, pipelineInfo):
    pipelineName = pipelineInfo.get("info").get("name")
    uuid = getPipeline(pipelineName).get("uuid")
    pipelineInfo["uuid"] = uuid
    stopPipeline_not_rest(ip, pipelineName)
    count = 0
    ret = None
    while count < 10:
        count += 1
        try:
            ret = postPipeline(pipelineName, pipelineInfo, ip)
        except Exception as e:
            time.sleep(0.5)
            continue
        if ret:
            break
    startPipeline_not_rest(ip, pipelineName)


def stopPipeline_not_rest(ip, pipelineName):
    # accord time list to stop pipeline
    stop_time_list = [1, 2, 5, 8, 10, 20, 60]
    try:
        stopPipeline(pipelineName, ip)
    except Exception as e:
        pass
    for t in stop_time_list:
        info = checkPipeline(pipelineName, ip)
        if info.get("status") == "STOPPED":
            break
        if info.get("status") == "STOPPING":
            time.sleep(t)
        if info.get("status") == "RUNNING":
            stopPipeline(pipelineName, ip)

    info = checkPipeline(pipelineName, ip)
    if info.get("status") == 'STOPPING':
        forceStopPipeline(pipelineName, ip)


def checkPipeline_not_rest_stop(ip, pipelineName):
    pipeline_info = checkPipeline(pipelineName, ip)
    status = pipeline_info.get("status")
    if status == "STOPPED":
        return True
    else:
        return False


def checkPipeline_not_rest(ip, pipelineName):
    pipeline_info = checkPipeline(pipelineName, ip)
    status = pipeline_info.get("status")
    if status == "RUNNING":
        return True
    else:
        return False


def startPipeline_not_rest(ip, pipelineName):
    if not checkPipeline_not_rest(ip, pipelineName):
        startPipeline(pipelineName, ip)


# 获取pipeline history status PathParam  /pipeline/{pipelineName}/history GET
def getPipelineHistory(pipelineName, ip="127.0.0.1"):
    orchid.setHost(ip)
    if orchid.get("/pipeline/" + pipelineName + "/history"):
        return orchid.getResult()
    else:
        # 检查 返回码 抛出异常 getCode
        raise Exception("streamsets rest failed, ip[%s] url [%s] method [GET], response Error [%s]" % (
            ip, "/pipeline/history" + pipelineName, orchid.getError()))


def main():
    # ret = getPipelines('access', 'false', '10.65.169.179')
    # ret = exportPipeline("de0625cc-1e93-477b-8565-571484ee3168",'10.65.169.179')
    print '====================='
    # print getPipeline("de0625cc-1e93-477b-8565-571484ee3168",'10.65.169.179')
    print stopPipeline_not_rest("10.65.169.180", "47f13d05-4d85-4ee0-913d-81d6fdd80530")
    # print startPipeline_not_rest("10.65.169.179", "47f13d05-4d85-4ee0-913d-81d6fdd80530")
    # print str(ret)


if __name__ == '__main__':
    main()